/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.lczyfz.wisdom.modules.sys.vueweb;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lczyfz.wisdom.common.config.Global;
import com.lczyfz.wisdom.common.utils.ResponseCode;
import com.lczyfz.wisdom.common.utils.ServerResponse;
import com.lczyfz.wisdom.common.utils.StringUtils;
import com.lczyfz.wisdom.common.web.BaseController;
import com.lczyfz.wisdom.modules.sys.entity.*;
import com.lczyfz.wisdom.modules.sys.service.AreaService;
import com.lczyfz.wisdom.modules.sys.service.OfficeService;
import com.lczyfz.wisdom.modules.sys.service.SystemService;
import com.lczyfz.wisdom.modules.sys.utils.DictUtils;
import com.lczyfz.wisdom.modules.sys.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 机构Controller
 * @author ThinkGem
 * @version 2013-5-15
 */
@Api(value = "office")
@RestController
@RequestMapping(value = "${apiPath}/sys/office")
public class OfficeVueController extends BaseController {
	@Autowired
	private SystemService systemService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private AreaService areaService;
	@ApiOperation(value = "获取机构列表",notes = "")
	@RequiresPermissions("sys:office:view")
	@RequestMapping(value = "search",method = RequestMethod.POST) //菜单列表
	public ServerResponse<Office> search(@RequestBody Office office) {
		boolean isAll = true;
        List<Office> list = officeService.findList(isAll);
        List<Office> officeList = new LinkedList<Office>();
        for (int i=0; i<list.size(); i++){
            Office e = list.get(i);
            if ((StringUtils.isBlank(office.getId()) || (office.getId()!=null && !office.getId().equals(e.getId()) && e.getParentIds().indexOf(","+office.getId()+",")==-1))
                    && (office.getType() == null || (office.getType()  != null && (!office.getType().equals("1") || office.getType().equals(e.getType()))))
                    && (office.getGrade() == null || (office.getGrade() != null && Integer.parseInt(e.getGrade()) <= Integer.parseInt(office.getGrade()))
                    && Global.YES.equals(e.getUseable()))){
                 officeList.add(e);
            }
        }
		return new ServerResponse<Office>(ResponseCode.SUCCESS.getCode(),officeList) ;
	}
	@ApiOperation(value = "通过机构office获取详情",notes = "获取详情")
	@RequiresPermissions("sys:office:view")
	@RequestMapping(value = "findById/{id}",method = RequestMethod.GET)
	public  ServerResponse<Office> form(@PathVariable String id) {
		Office office =officeService.get(id);
		office.setAreaId(office.getArea().getId());
		User user = UserUtils.getUser();
		if (StringUtils.isBlank(office.getParent().getId())){
			office.setParent(user.getOffice());
			office.setOfficeParentId(user.getOffice().getId());
		}else if(StringUtils.isNotBlank(office.getParentId())){
			office.setParent(officeService.get(office.getParentId()));
			office.setOfficeParentId(office.getParentId());
		}else {
			office.setOfficeParentId(office.getParentId());
		}
		if(office.getPrimaryPerson()!=null){
			office.setPrimaryPersonId(office.getPrimaryPerson().getId());
		}
		if(office.getDeputyPerson()!=null){
			office.setDeputyPersonId(office.getDeputyPerson().getId());
		}
		if (office.getArea()==null){
			office.setArea(user.getOffice().getArea());
		}
		// 自动获取排序号
		if (StringUtils.isBlank(office.getId())&&office.getParent()!=null){
			int size = 0;
			List<Office> list = officeService.findAll();
			for (int i=0; i<list.size(); i++){
				Office e = list.get(i);
				if (e.getParent()!=null && e.getParent().getId()!=null
						&& e.getParent().getId().equals(office.getParent().getId())){
					size++;
				}
			}
			office.setCode(office.getParent().getCode() + StringUtils.leftPad(String.valueOf(size > 0 ? size+1 : 1), 3, "0"));
		}
		return  new ServerResponse(ResponseCode.SUCCESS.getCode(),office) ;
	}
	@ApiOperation(value = "添加和更新机构",notes = "添加机构")
	@RequiresPermissions("sys:office:edit")
	@RequestMapping(value = "save",method = RequestMethod.POST) //更新机构
	public ServerResponse<String> update(@RequestBody Office office) {
		if(StringUtils.isNotBlank(office.getOfficeParentId())){
			office.setParent(officeService.get(office.getOfficeParentId()));
		}
		if(StringUtils.isNotBlank(office.getAreaId())){
			office.setArea(areaService.get(office.getAreaId()));
		}else {
			return ServerResponse.createByErrorMessage("区域不能为空");
		}
		if(Global.isDemoMode()){
			return ServerResponse.createByErrorMessage("演示模式，不允许操作！");
		}
		if(StringUtils.isNotBlank(office.getPrimaryPersonId())){
            office.setPrimaryPerson(systemService.getUser(office.getPrimaryPersonId()));
		}
		if(StringUtils.isNotBlank(office.getDeputyPersonId())){
			office.setDeputyPerson(systemService.getUser(office.getDeputyPersonId()));
		}
		officeService.save(office);
		if(office.getChildDeptList()!=null){
			Office childOffice = null;
			for(String id : office.getChildDeptList()){
				childOffice = new Office();
				childOffice.setName(DictUtils.getDictLabel(id, "sys_office_common", "未知"));
				childOffice.setParent(office);
				childOffice.setArea(office.getArea());
				childOffice.setType("2");
				childOffice.setGrade(String.valueOf(Integer.valueOf(office.getGrade())+1));
				officeService.save(childOffice);
				childOffice.setUseable(Global.YES);
			}
		}
	//	String id = "0".equals(office.getParentId()) ? "" : office.getParentId();
		return ServerResponse.createBySuccessMessage("保存机构"+ office.getName() + "成功");
	}
    @ApiOperation(value = "删除机构",notes = "根据url的id来指定删除对象")
	@RequiresPermissions("sys:office:edit")
	@RequestMapping(value = "delete",method = RequestMethod.DELETE) //删除机构
	public ServerResponse<String> delete(@RequestBody Office office) {
		if(Global.isDemoMode()){
			return ServerResponse.createByErrorMessage("演示模式，不允许操作！");
		}
		officeService.delete(office);
		return ServerResponse.deleteBySuccessMessage("删除机构成功！");
	}

	/**
	 * 获取机构JSON数据。
	 * @param extId 排除的ID
	 * @param type	类型（1：公司；2：部门/小组/其它：3：用户）
	 * @param grade 显示级别
	 * @param response
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData", method = RequestMethod.GET)
	@ApiOperation(value = "获取组织机构树形图")
	public ServerResponse<List<Map<String, Object>>> treeData(@RequestParam(required=false) String extId, @RequestParam(required=false) String type,
											  @RequestParam(required=false) Long grade, @RequestParam(required=false) Boolean isAll) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<Office> list = officeService.findList(isAll);
		for (int i=0; i<list.size(); i++){
			Office e = list.get(i);
			if ((StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1))
					&& (type == null || (type != null && (!type.equals("1") || type.equals(e.getType()))))
					&& (grade == null || (grade != null && Integer.parseInt(e.getGrade()) <= grade.intValue()))
					&& Global.YES.equals(e.getUseable())){
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("pIds", e.getParentIds());
				map.put("name", e.getName());
				if (type != null && "3".equals(type)){
					map.put("isParent", true);
				}
				mapList.add(map);
			}
		}
		return new ServerResponse(ResponseCode.SUCCESS.getCode(), mapList);
	}
}
